package cn.com.yang.egg;

import javassist.*;
import org.junit.Test;

/**
 * @Author 杨亿金
 * @Date 2022/1/24 20:36
 * @CopyRight
 * @Version
 */
public class JavaAssisDemo {

    @Test
    public void createDemoClass() throws Exception{
        ClassPool pool = ClassPool.getDefault();
        //1.创建一个空类
        CtClass cc = pool.makeClass("cn.com.yang.egg.PersonNew");
        //2.新增一个字段 private String name
        CtField param = new CtField(pool.get("java.lang.String"),"name",cc);
        param.setModifiers(Modifier.PRIVATE);
        //初始化值
        cc.addField(param,CtField.Initializer.constant("xiao yang"));
        //3.生成getter setter方法
        cc.addMethod(CtNewMethod.setter("setName",param));
        cc.addMethod(CtNewMethod.getter("getName",param));
        //4.添加无参构造器
        CtConstructor constructor = new CtConstructor(new CtClass[]{},cc);
        constructor.setBody("{name=\"xiaohua\";}");
        cc.addConstructor(constructor);
        //5.添加有参构造器
        constructor=new CtConstructor(new CtClass[]{pool.get("java.lang.String")},cc);
        //$0代表this /$1 $2...代表参数
        constructor.setBody("{$0.name=$1;}");
        //6.创建一个名为printName的方法，无参数，无返回值，输出name
        CtMethod method = new CtMethod(CtClass.voidType,"printName",new CtClass[]{},cc);
        method.setModifiers(Modifier.PUBLIC);
        method.setBody("{System.out.print(name);}");
        cc.addMethod(method);
        //7.编译文件
        cc.writeFile("/cn/com/yang/egg");
    }
}
